<template>
  <el-form ref="form" :model="form" label-width="80px">
    <el-form-item label="分类名称">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item label="排序">
      <el-input v-model="form.sort" type="number"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">确 定</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import {
  createOrEditCategory as createOrUpdate,
  getCategory
} from '@/services/resource'
import { wrapAsyncWithLoading } from '@/utils/helper'
import { Form } from 'element-ui'
import Vue from 'vue'
export default Vue.extend({
  name: 'CategoryCreateOrEditForm',
  props: ['id'],
  data () {
    return {
      locking: false,
      form: {
        name: 'test_lnw_',
        sort: 0
      }
    }
  },
  created () {
    console.log('created', this.id)
    wrapAsyncWithLoading(this, 'locking', 'loadFormData')
    this.loadFormData()
    this.$emit('register', this.submit.bind(this))
  },
  methods: {
    async loadFormData () {
      if (!this.id) return
      const { data } = await getCategory(this.id)
      if (data.code === '000000') {
        if (!data.data) {
          this.$emit('fatal', '资源不存在')
          return
        }
        this.form = data.data
      }
    },
    async submit () {
      const form = this.$refs.form as Form
      try {
        await form.validate()
      } catch (error) {
        return
      }
      try {
        const { data } = await createOrUpdate(this.form)
        if (data.code === '000000') {
          this.$emit('suc', data)
        } else {
          this.$emit('fail', data)
        }
      } catch (error) {
        this.$emit('fail', error)
      }
    }
  }
})
</script>
